package com.douyang.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.douyang.base.enumeration.GoodsTypeEnum;
import com.douyang.base.enumeration.PayOrderStatusEnum;
import com.douyang.base.expcetion.TradeException;
import com.douyang.base.model.PageResult;
import com.douyang.base.utils.IdWorkerUtils;
import com.douyang.base.utils.UserUtil;
import com.douyang.dto.MyOrderListDTO;
import com.douyang.dto.PayOrderDTO;
import com.douyang.mapper.PayOrderBaseMapper;

import com.douyang.model.PayOrderBase;
import com.douyang.model.PayOrderDetail;
import com.douyang.model.SeckKill;
import com.douyang.service.PayOrderBaseService;
import com.douyang.service.PayOrderDetailService;
import com.douyang.service.SeckKillService;
import com.douyang.vo.MyOrderListVO;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2025-03-20
 */
@Service
public class PayOrderBaseServiceImpl extends ServiceImpl<PayOrderBaseMapper, PayOrderBase> implements PayOrderBaseService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PayOrderDetailService payOrderDetailService;

    @Autowired
    private SeckKillService seckKillService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    @Transactional
    public void createPayOrder(PayOrderDTO payOrderDTO) {
        String checkId = payOrderDTO.getCheckId();
        if (checkId == null) {throw new TradeException("checkId参数缺失");}
        Long removed = stringRedisTemplate.opsForSet().remove("checkIdList", checkId);
        if (removed==null || removed == 0) return;



        PayOrderBase payOrderBase = new PayOrderBase();
        BeanUtils.copyProperties(payOrderDTO, payOrderBase);
        long orderId = IdWorkerUtils.getInstance().nextId();
        payOrderBase.setOrderId(orderId);
        save(payOrderBase);

        SeckKill seckKill = seckKillService.getById(payOrderDTO.getGoodsId());
        PayOrderDetail payOrderDetail = PayOrderDetail.builder()
                .orderId(orderId)
                .orderStatus(PayOrderStatusEnum.CREATE)
                .createTime(LocalDateTime.now())
                .orderDescribe(seckKill.getTitle())
                .orderTitle(seckKill.getName())
                .price(seckKill.getPrice())
                .build();
        BeanUtils.copyProperties(seckKill, payOrderDetail);
        payOrderDetailService.save(payOrderDetail);

        if(payOrderDTO.getGoodsType().equals(GoodsTypeEnum.SECKKILL))
            seckKillService.lambdaUpdate()
                    .eq(SeckKill::getId,payOrderDTO.getGoodsId())
                    .setSql("stock=stock-1")
                    .update();


        rabbitTemplate.convertAndSend("trade.direct2", "checkOrder", orderId, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay(5*60*1000);
                return message;
            }
        });

    }

    @Override
    public PageResult<MyOrderListVO> getMyOrders(MyOrderListDTO myOrderListDTO) {
        Page<PayOrderDetail> page = myOrderListDTO.getPage();

        List<PayOrderBase> payOrderBaseList = lambdaQuery()
                .select(PayOrderBase::getOrderId)
                .eq(PayOrderBase::getUserId, UserUtil.getLoginUserBaseInfo().getId())
                .list();

        if(CollectionUtils.isEmpty(payOrderBaseList)){
            return new PageResult<>(List.of(),0,1,10);
        }

        List<Long> orderIdList = payOrderBaseList.stream().map(PayOrderBase::getOrderId).toList();

       page = payOrderDetailService.lambdaQuery()
                .in(PayOrderDetail::getOrderId, orderIdList)
                .eq(StringUtils.isNotEmpty(myOrderListDTO.getProductName()), PayOrderDetail::getOrderTitle, myOrderListDTO.getProductName())
                .like(myOrderListDTO.getOrderId() != null, PayOrderDetail::getOrderId, myOrderListDTO.getOrderId())
                .eq(myOrderListDTO.getStatus() != null, PayOrderDetail::getOrderStatus, myOrderListDTO.getStatus())
                .orderByDesc(PayOrderDetail::getCreateTime)
                .page(page);

        return PageResult.of(page,payOrderDetail -> {
            MyOrderListVO myOrderListVO = new MyOrderListVO();
            BeanUtils.copyProperties(payOrderDetail, myOrderListVO);
            return myOrderListVO;
        });
    }
}
